using B.S.Data.MES.API.Models;
using B.S.Domain.Dto.AICustomerServiceDTO;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Text.Json;

namespace B.S.Data.MES.API.Services
{
    /// <summary>
    /// 科大讯飞AI服务实现
    /// </summary>
    public class XunFeiService : IXunFeiService
    {
        private readonly XunFeiConfig _config;
        private readonly IDataQueryService _dataQueryService;
        private readonly HttpClient _httpClient;
        private readonly ILogger<XunFeiService> _logger;

        public XunFeiService(
            IOptions<XunFeiConfig> config,
            IDataQueryService dataQueryService,
            HttpClient httpClient,
            ILogger<XunFeiService> logger)
        {
            _config = config.Value;
            _dataQueryService = dataQueryService;
            _httpClient = httpClient;
            _logger = logger;
        }

        /// <summary>
        /// 发送聊天请求到科大讯飞API
        /// </summary>
        public async Task<string> ChatAsync(string message, List<ConversationHistory>? history = null)
        {
            try
            {
                // 优先使用新的HTTP API
                if (!string.IsNullOrEmpty(_config.BearerToken))
                {
                    return await ChatWithHttpApiAsync(message, history);
                }
                
                // 回退到WebSocket API
                return await ChatWithWebSocketApiAsync(message, history);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "调用科大讯飞API异常: {Message}", ex.Message);
                return "抱歉，AI服务出现异常，请稍后再试。";
            }
        }

        /// <summary>
        /// 使用HTTP API进行聊天
        /// </summary>
        private async Task<string> ChatWithHttpApiAsync(string message, List<ConversationHistory>? history = null)
        {
            try
            {
                _logger.LogInformation("开始HTTP API调用，消息: {Message}", message);
                _logger.LogInformation("配置检查 - BearerToken存在: {HasToken}, URL: {Url}", 
                    !string.IsNullOrEmpty(_config.BearerToken), _config.HttpApiUrl);

                var request = new XunFeiHttpRequest
                {
                    max_tokens = _config.MaxTokens,
                    temperature = _config.Temperature,
                    model = _config.Model,
                    stream = _config.EnableStream,
                    messages = BuildHttpMessageHistory(message, history)
                };

                var jsonRequest = System.Text.Json.JsonSerializer.Serialize(request, new JsonSerializerOptions
                {
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
                });

                _httpClient.DefaultRequestHeaders.Clear();
                _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {_config.BearerToken}");
                _httpClient.Timeout = TimeSpan.FromSeconds(_config.TimeoutSeconds);

                var content = new StringContent(jsonRequest, Encoding.UTF8, "application/json");

                _logger.LogInformation("发送HTTP请求到科大讯飞API: {Url}", _config.HttpApiUrl);
                _logger.LogInformation("请求头Authorization: Bearer {TokenPrefix}...", 
                    _config.BearerToken?.Length > 10 ? _config.BearerToken.Substring(0, 10) : "无");
                _logger.LogDebug("完整请求内容: {Request}", jsonRequest);

                var response = await _httpClient.PostAsync(_config.HttpApiUrl, content);
                
                _logger.LogInformation("收到响应，状态码: {StatusCode}", response.StatusCode);
                
                if (!response.IsSuccessStatusCode)
                {
                    var errorContent = await response.Content.ReadAsStringAsync();
                    _logger.LogError("科大讯飞HTTP API调用失败: {StatusCode}, 错误内容: {Content}", 
                        response.StatusCode, errorContent);
                    return $"API调用失败 ({response.StatusCode}): {errorContent}";
                }

                // 处理流式响应
                if (_config.EnableStream)
                {
                    _logger.LogInformation("处理流式响应");
                    return await ProcessStreamResponseAsync(response);
                }
                else
                {
                    _logger.LogInformation("处理普通响应");
                    return await ProcessNormalResponseAsync(response);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "HTTP API调用异常: {Message}, StackTrace: {StackTrace}", 
                    ex.Message, ex.StackTrace);
                return $"API调用异常: {ex.Message}";
            }
        }

        /// <summary>
        /// 处理流式响应
        /// </summary>
        private async Task<string> ProcessStreamResponseAsync(HttpResponseMessage response)
        {
            var fullResponse = new StringBuilder();
            var lineCount = 0;
            
            try
            {
                _logger.LogInformation("开始处理流式响应");
                
                using var stream = await response.Content.ReadAsStreamAsync();
                using var reader = new StreamReader(stream, Encoding.UTF8);
                
                string? line;
                while ((line = await reader.ReadLineAsync()) != null)
                {
                    lineCount++;
                    _logger.LogDebug("收到流式数据行 {LineCount}: {Line}", lineCount, line);
                    
                    if (string.IsNullOrWhiteSpace(line)) continue;
                    
                    // 处理 "data: " 前缀
                    if (line.StartsWith("data: "))
                    {
                        var jsonData = line.Substring(6).Trim();
                        
                        // 检查是否为结束标记
                        if (jsonData == "[DONE]")
                        {
                            _logger.LogInformation("收到流式响应结束标记");
                            break;
                        }
                        
                        try
                        {
                            var streamResponse = System.Text.Json.JsonSerializer.Deserialize<XunFeiHttpResponse>(jsonData, new JsonSerializerOptions
                            {
                                PropertyNamingPolicy = JsonNamingPolicy.CamelCase
                            });
                            
                            var choice = streamResponse?.choices?.FirstOrDefault();
                            var deltaContent = choice?.delta?.content;
                            
                            if (!string.IsNullOrEmpty(deltaContent))
                            {
                                fullResponse.Append(deltaContent);
                                _logger.LogDebug("累积内容长度: {Length}", fullResponse.Length);
                            }
                        }
                        catch (System.Text.Json.JsonException ex)
                        {
                            _logger.LogWarning("解析流式JSON失败: {Error}, 数据: {Data}", ex.Message, jsonData);
                        }
                    }
                    else
                    {
                        // 尝试直接解析整行JSON
                        try
                        {
                            var streamResponse = System.Text.Json.JsonSerializer.Deserialize<XunFeiHttpResponse>(line, new JsonSerializerOptions
                            {
                                PropertyNamingPolicy = JsonNamingPolicy.CamelCase
                            });
                            
                            var choice = streamResponse?.choices?.FirstOrDefault();
                            var deltaContent = choice?.delta?.content ?? choice?.message?.content;
                            
                            if (!string.IsNullOrEmpty(deltaContent))
                            {
                                fullResponse.Append(deltaContent);
                                _logger.LogDebug("直接解析累积内容长度: {Length}", fullResponse.Length);
                            }
                        }
                        catch (System.Text.Json.JsonException)
                        {
                            // 忽略无法解析的行
                        }
                    }
                }
                
                var result = fullResponse.ToString();
                _logger.LogInformation("流式响应处理完成，总行数: {LineCount}, 最终内容长度: {Length}", 
                    lineCount, result.Length);
                
                if (string.IsNullOrEmpty(result))
                {
                    _logger.LogWarning("流式响应处理完成但内容为空");
                    return "抱歉，没有获取到AI回复内容。";
                }
                
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理流式响应异常: {Message}", ex.Message);
                return $"处理流式响应异常: {ex.Message}";
            }
        }

        /// <summary>
        /// 处理普通响应
        /// </summary>
        private async Task<string> ProcessNormalResponseAsync(HttpResponseMessage response)
        {
            try
            {
                var responseContent = await response.Content.ReadAsStringAsync();
                _logger.LogInformation("收到普通响应，长度: {Length}", responseContent.Length);
                _logger.LogDebug("响应内容: {Response}", responseContent);
                
                if (string.IsNullOrEmpty(responseContent))
                {
                    _logger.LogWarning("响应内容为空");
                    return "抱歉，收到了空的响应内容。";
                }
                
                var xunfeiResponse = System.Text.Json.JsonSerializer.Deserialize<XunFeiHttpResponse>(responseContent, new JsonSerializerOptions
                {
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
                });
                
                if (xunfeiResponse?.choices == null || !xunfeiResponse.choices.Any())
                {
                    _logger.LogWarning("响应中没有choices数据");
                    return $"响应格式异常，原始内容: {responseContent.Substring(0, Math.Min(200, responseContent.Length))}...";
                }
                
                var choice = xunfeiResponse.choices.FirstOrDefault();
                var aiResponse = choice?.message?.content;
                
                if (string.IsNullOrEmpty(aiResponse))
                {
                    _logger.LogWarning("choices中没有有效的message.content");
                    return $"AI回复为空，原始响应: {responseContent.Substring(0, Math.Min(200, responseContent.Length))}...";
                }
                
                _logger.LogInformation("成功解析AI回复，长度: {Length}", aiResponse.Length);
                return aiResponse;
            }
            catch (System.Text.Json.JsonException ex)
            {
                _logger.LogError(ex, "JSON解析异常: {Message}", ex.Message);
                return $"响应解析失败: {ex.Message}";
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理普通响应异常: {Message}", ex.Message);
                return $"处理响应异常: {ex.Message}";
            }
        }

        /// <summary>
        /// 使用WebSocket API进行聊天（原有方法，作为备用）
        /// </summary>
        private async Task<string> ChatWithWebSocketApiAsync(string message, List<ConversationHistory>? history = null)
        {
            try
            {
                var authUrl = GenerateAuthUrl(_config.BaseUrl);
                
                var request = new XunFeiChatRequest
                {
                    Header = new XunFeiHeader
                    {
                        app_id = _config.AppId,
                        uid = Guid.NewGuid().ToString("N")[..16]
                    },
                    Parameter = new XunFeiParameter
                    {
                        Chat = new XunFeiChat
                        {
                            domain = _config.Domain,
                            temperature = _config.Temperature,
                            max_tokens = _config.MaxTokens
                        }
                    },
                    Payload = new XunFeiPayload
                    {
                        Message = new XunFeiMessage
                        {
                            Text = BuildMessageHistory(message, history)
                        }
                    }
                };

                var jsonRequest = JsonConvert.SerializeObject(request);
                var content = new StringContent(jsonRequest, Encoding.UTF8, "application/json");

                _logger.LogInformation("发送WebSocket请求到科大讯飞API: {Url}", authUrl);
                
                var response = await _httpClient.PostAsync(authUrl, content);
                var responseContent = await response.Content.ReadAsStringAsync();

                if (!response.IsSuccessStatusCode)
                {
                    _logger.LogError("科大讯飞WebSocket API调用失败: {StatusCode}, {Content}", response.StatusCode, responseContent);
                    return "抱歉，AI服务暂时不可用，请稍后再试。";
                }

                var xunfeiResponse = JsonConvert.DeserializeObject<XunFeiChatResponse>(responseContent);
                
                if (xunfeiResponse?.Header?.code != 0)
                {
                    _logger.LogError("科大讯飞WebSocket API返回错误: {Code}, {Message}", 
                        xunfeiResponse?.Header?.code, xunfeiResponse?.Header?.message);
                    return "抱歉，AI服务返回了错误，请稍后再试。";
                }

                var aiResponse = xunfeiResponse?.Payload?.Choices?.text?.FirstOrDefault()?.content ?? "抱歉，没有获取到回复。";
                return aiResponse;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "WebSocket API调用异常: {Message}", ex.Message);
                return "抱歉，AI服务出现异常，请稍后再试。";
            }
        }

        /// <summary>
        /// 智能助手对话，集成项目数据查询
        /// </summary>
        public async Task<AIAssistantResponse> SmartChatAsync(AIAssistantRequest request)
        {
            var stopwatch = Stopwatch.StartNew();
            
            try
            {
                _logger.LogInformation("收到智能助手请求: {Message}", request.Message);

                // 判断是否需要数据查询
                var needDataQuery = IsDataQueryNeeded(request.Message);
                var dataResult = new DataQueryResult { Success = false };
                
                if (needDataQuery)
                {
                    dataResult = await _dataQueryService.QueryDataByQuestion(request.Message);
                }

                // 构建对话历史
                var fullHistory = new List<ConversationHistory>();
                if (request.History?.Any() == true)
                {
                    fullHistory.AddRange(request.History.TakeLast(6)); // 保留最近6轮对话
                }

                // 选择消息内容
                var messageToSend = needDataQuery && dataResult.Success 
                    ? BuildEnhancedMessage(request.Message, dataResult)
                    : request.Message;

                // 调用科大讯飞API获取智能回复
                var aiResponse = await ChatAsync(messageToSend, fullHistory);

                stopwatch.Stop();

                return new AIAssistantResponse
                {
                    Response = aiResponse,
                    SessionId = request.SessionId,
                    Suggestions = GenerateContextualSuggestions(request.Message, dataResult),
                    DataType = dataResult.DataType ?? "对话",
                    DataCount = dataResult.DataCount,
                    HasData = dataResult.Success && dataResult.DataCount > 0,
                    ProcessingTime = stopwatch.ElapsedMilliseconds
                };
            }
            catch (Exception ex)
            {
                stopwatch.Stop();
                _logger.LogError(ex, "智能助手对话异常: {Message}", ex.Message);
                
                return new AIAssistantResponse
                {
                    Response = "抱歉，我遇到了一些技术问题，请稍后再试或换个问题吧 😅",
                    SessionId = request.SessionId,
                    Suggestions = new List<string> { "重新提问", "查看帮助", "联系客服" },
                    DataType = "错误",
                    DataCount = 0,
                    HasData = false,
                    ProcessingTime = stopwatch.ElapsedMilliseconds
                };
            }
        }

        /// <summary>
        /// 判断是否需要数据查询
        /// </summary>
        private bool IsDataQueryNeeded(string message)
        {
            var queryKeywords = new[] { "查询", "查看", "显示", "获取", "统计", "列表", "信息", "数据", "工单", "物料", "客户", "仓库" };
            var lowerMessage = message.ToLower();
            
            return queryKeywords.Any(keyword => lowerMessage.Contains(keyword));
        }

        /// <summary>
        /// 生成上下文相关的建议
        /// </summary>
        private List<string> GenerateContextualSuggestions(string userMessage, DataQueryResult dataResult)
        {
            var lowerMessage = userMessage.ToLower();
            
            if (lowerMessage.Contains("工单"))
                return new List<string> { "查看工单详情", "工单进度如何", "今天的工单" };
            
            if (lowerMessage.Contains("物料"))
                return new List<string> { "物料库存情况", "缺料预警", "物料清单" };
            
            if (lowerMessage.Contains("客户"))
                return new List<string> { "客户联系方式", "客户订单", "新增客户" };
            
            if (lowerMessage.Contains("仓库"))
                return new List<string> { "库存盘点", "出入库记录", "仓库容量" };
            
            return GenerateDefaultSuggestions();
        }

        /// <summary>
        /// 生成鉴权URL
        /// </summary>
        public string GenerateAuthUrl(string url)
        {
            try
            {
                var uri = new Uri(url);
                var host = uri.Host;
                var path = uri.AbsolutePath;
                var httpDate = DateTime.UtcNow.ToString("r");

                // 构造签名字符串
                var signatureString = $"host: {host}\ndate: {httpDate}\nGET {path} HTTP/1.1";
                
                // 使用API Secret进行HMAC-SHA256签名
                var keyBytes = Encoding.UTF8.GetBytes(_config.ApiSecret);
                var dataBytes = Encoding.UTF8.GetBytes(signatureString);
                
                using var hmac = new HMACSHA256(keyBytes);
                var signatureBytes = hmac.ComputeHash(dataBytes);
                var signature = Convert.ToBase64String(signatureBytes);

                // 构造Authorization
                var authorization = $"api_key=\"{_config.ApiKey}\", algorithm=\"hmac-sha256\", headers=\"host date request-line\", signature=\"{signature}\"";
                var authorizationBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(authorization));

                // 构造最终URL
                var finalUrl = $"{url}?authorization={HttpUtility.UrlEncode(authorizationBase64)}&date={HttpUtility.UrlEncode(httpDate)}&host={HttpUtility.UrlEncode(host)}";
                
                return finalUrl;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成鉴权URL失败: {Message}", ex.Message);
                return url;
            }
        }

        /// <summary>
        /// 构建消息历史（WebSocket API使用）
        /// </summary>
        private List<XunFeiMessageItem> BuildMessageHistory(string currentMessage, List<ConversationHistory>? history)
        {
            var messages = new List<XunFeiMessageItem>();

            // 添加历史消息
            if (history?.Any() == true)
            {
                foreach (var item in history.TakeLast(10)) // 最多保留10条历史记录
                {
                    messages.Add(new XunFeiMessageItem
                    {
                        role = item.Role,
                        content = item.Content
                    });
                }
            }

            // 添加当前消息
            messages.Add(new XunFeiMessageItem
            {
                role = "user",
                content = currentMessage
            });

            return messages;
        }

        /// <summary>
        /// 构建HTTP API消息历史
        /// </summary>
        private List<XunFeiHttpMessage> BuildHttpMessageHistory(string currentMessage, List<ConversationHistory>? history)
        {
            var messages = new List<XunFeiHttpMessage>();

            // 科大讯飞API不支持system角色，将系统提示合并到用户消息中
            var enhancedMessage = currentMessage;
            
            // 如果是第一次对话（没有历史），添加系统提示
            if (history?.Any() != true)
            {
                var systemPrompt = BuildSystemPrompt();
                enhancedMessage = $"{systemPrompt}\n\n用户问题：{currentMessage}";
            }

            // 添加历史消息
            if (history?.Any() == true)
            {
                foreach (var item in history.TakeLast(10)) // 保留最近10轮对话
                {
                    // 确保角色只能是user或assistant
                    var role = item.Role.ToLower();
                    if (role == "system") continue; // 跳过系统消息
                    
                    messages.Add(new XunFeiHttpMessage
                    {
                        role = role == "user" ? "user" : "assistant",
                        content = item.Content
                    });
                }
            }

            // 添加当前用户消息
            messages.Add(new XunFeiHttpMessage
            {
                role = "user",
                content = enhancedMessage
            });

            return messages;
        }

        /// <summary>
        /// 构建系统提示词
        /// </summary>
        private string BuildSystemPrompt()
        {
            return @"你是一个智能、友好的MES制造执行系统助手。请用自然、亲切的语气与用户交流，就像一个经验丰富的同事一样。

你的特点：
- 语言自然流畅，不要过于正式或机械化
- 善于理解用户意图，提供实用的帮助
- 适当使用表情符号让对话更生动
- 遇到不确定的问题会诚实说明，并提供替代方案

你可以帮助用户：
• 查询工单、物料、客户、仓库等信息
• 解释系统功能和操作方法
• 提供生产管理建议
• 解答日常使用问题

请用简洁明了的语言回答，避免冗长的格式化输出。如果用户只是打招呼或闲聊，请友好回应。";
        }

        /// <summary>
        /// 构建增强消息
        /// </summary>
        private string BuildEnhancedMessage(string originalMessage, DataQueryResult dataResult)
        {
            if (!dataResult.Success || string.IsNullOrEmpty(dataResult.Answer))
            {
                return originalMessage;
            }

            return $@"用户问题：{originalMessage}

相关数据：{dataResult.Answer}

请用自然的语言回答用户问题，直接给出有用的信息，不需要过多格式化。";
        }

        /// <summary>
        /// 合并数据查询结果和AI回复
        /// </summary>
        private string CombineDataAndAIResponse(DataQueryResult dataResult, string aiResponse)
        {
            if (string.IsNullOrEmpty(dataResult.Answer))
            {
                return aiResponse;
            }

            // 如果AI已经很好地整合了数据，直接返回AI回复
            if (aiResponse.Length > 100 && !aiResponse.Contains("抱歉") && !aiResponse.Contains("无法"))
            {
                return aiResponse;
            }

            // 否则提供简洁的数据回复
            return $"{aiResponse}\n\n{dataResult.Answer}";
        }

        /// <summary>
        /// 生成默认建议
        /// </summary>
        private List<string> GenerateDefaultSuggestions()
        {
            return new List<string>
            {
                "我想看看工单情况",
                "物料库存怎么样", 
                "有哪些客户信息",
                "仓库现在什么状态",
                "系统数据统计",
                "需要人工帮助"
            };
        }
    }
}
